

src = "https://cdn.jsdelivr.net/npm/leancloud-storage/dist/av-min.js"
function initLeanCloud() {
    const appId = "ynMAn7XOvvxivG61hKnibx0P-gzGzoHsz";
    const appKey = "bJozAX2UEPCNqmriHhTiceIc";
    const serverURL = "https://api.lintiebao.cn";
    AV.init({ appId, appKey, serverURL });
}

function requestData(currentPage, pageSize, keyword, callback) {
    const first = new AV.Query("guwen");
    first.contains("writer", keyword);
    const second = new AV.Query("guwen");
    second.contains("content", keyword);
    const third = new AV.Query("guwen");
    third.contains("title", keyword);
    const query = AV.Query.or(first, second, third);
    query.limit(pageSize);
    query.skip((currentPage - 1) * pageSize);
    // 查询数据
    query.find().then(function (results) {
        // 处理查询结果
        var poemList = document.getElementById('poem-list');

        results.forEach(function (object) {
            // 将数据展示在 HTML 页面上
            var contentData = object.get('content');
            var titleData = object.get('title');
            var writerData = object.get('writer');
            var dynastyData = object.get('dynasty');
            var remarkData = object.get('remark');
            var translationData = object.get('translation');
            var shangxiData = object.get('shangxi');


            var card = document.createElement('div');
            card.classList.add('poem-card');

            var title = document.createElement('h5');
            title.classList.add('poem-title');
            title.textContent = titleData;

            var author = document.createElement('div');
            author.classList.add('poem-author');
            author.textContent = dynastyData + ' · ' + writerData;

            var content = document.createElement('div');
            content.classList.add('poem-content');
            content.textContent = contentData;

            card.appendChild(title);
            card.appendChild(author);
            card.appendChild(content);
            poemList.appendChild(card);

            // 为诗词卡片添加点击事件
            card.addEventListener('click', function () {
                // 在这里处理点击事件，例如跳转到诗词的详情页
                // window.location.href = 'poem-details.html?title=' + encodeURIComponent(titleData);

                localStorage.setItem('selectedPoemTitle', titleData);
                localStorage.setItem('selectedPoemAuthor', writerData);
                localStorage.setItem('selectedPoemContent', contentData);
                localStorage.setItem('selectedPoemRemark', remarkData);
                localStorage.setItem('selectedPoemTranslation', translationData);
                localStorage.setItem('selectedPoemShangxi', shangxiData);
                localStorage.setItem('selectedPoemDynasty', dynastyData);
                // 跳转到详情页
                window.location.href = 'poem-details.html';
            });

        });
        callback();
    }).catch(function (error) {
        // 处理错误
        console.error('Error while fetching data:', error);
        callback();
    });
}
function clean() {
    var dataContainer = document.getElementById('poem-list');
    // 清空容器
    dataContainer.innerHTML = '';
}

function requestFamousSentences(currentPage, pageSize, keyword, callback) {
    const first = new AV.Query("sentence");
    first.contains("from", keyword);
    const second = new AV.Query("sentence");
    second.contains("name", keyword);
    const query = AV.Query.or(first, second);
    query.limit(pageSize);
    query.skip((currentPage - 1) * pageSize);
    // 查询数据
    query.find().then(function (results) {
        // 处理查询结果
        var poemList = document.getElementById('poem-list');

        results.forEach(function (object,index) {
            // 将数据展示在 HTML 页面上
            var fromData = object.get('from');
            var nameData = object.get('name');
            var card = document.createElement('div');
            card.classList.add('poem-card');
            card.setAttribute('data-index', index);

            var title = document.createElement('h5');
            title.classList.add('poem-title');
            title.textContent = nameData;

            var author = document.createElement('div');
            author.classList.add('poem-author');
            author.textContent = fromData;

            card.appendChild(title);
            card.appendChild(author);
            poemList.appendChild(card);
            // 为诗词卡片添加点击事件
            card.addEventListener('click', function () {
                let clickedIndex = parseInt(this.getAttribute('data-index'));
                const serializedResults = JSON.stringify(results);
                localStorage.setItem('famousSentencesArray', serializedResults);
                localStorage.setItem('famousSentencesIndex', clickedIndex);
                window.location.href = 'famousSentencesDetail.html';
            });
        });
        callback();
    }).catch(function (error) {
        // 处理错误
        // console.error('Error while fetching data:', error);
        callback();
    });
}

function random_requestFamousSentences(currentPage, pageSize, keyword, callback) {
    const first = new AV.Query("sentence");
    first.contains("from", keyword);
    const second = new AV.Query("sentence");
    second.contains("name", keyword);
    const query = AV.Query.or(first, second);
    let randomNum = Math.floor(Math.random() * 12900);
    query.limit(pageSize);
    query.skip(randomNum);
    // 查询数据
    query.find().then(function (results) {
        // 处理查询结果
        callback(results);
    }).catch(function (error) {
        // 处理错误
        // console.error('Error while fetching data:', error);
        // callback();
    });
}

function requestSpringCouplet(currentPage, pageSize, keyword, callback) {

    const first = new AV.Query("SpringCouplets");
    first.contains("shang", keyword);
    const second = new AV.Query("SpringCouplets");
    second.contains("xia", keyword);
    const query = AV.Query.or(first, second);
    query.limit(pageSize);
    query.skip((currentPage - 1) * pageSize);
    // 查询数据
    query.find().then(function (results) {
        // 处理查询结果
        var poemList = document.getElementById('poem-list');
        results.forEach(function (object,index) {

            // 将数据展示在 HTML 页面上
            var shangData = object.get('shang');
            var xiaData = object.get('xia');
            var card = document.createElement('div');
            card.classList.add('poem-card');
            card.setAttribute('data-index', index);

            var shang = document.createElement('h5');
            shang.classList.add('poem-title');
            shang.textContent = shangData;

            var xia = document.createElement('h5');
            xia.classList.add('poem-title');
            xia.textContent = xiaData;

            card.appendChild(shang);
            card.appendChild(xia);
            poemList.appendChild(card);
            // 为诗词卡片添加点击事件
            card.addEventListener('click', function () {
                // const inputText = document.getElementById("text-animate");
                const text = shangData + xiaData;
                localStorage.setItem('jiziInputContent', text);
                window.location.href = 'jizi2_next.html';
            });
        });
        callback();
    }).catch(function (error) {
        // 处理错误
        // console.error('Error while fetching data:', error);
        // callback();
    });
}
function requestZitie_today(currentPage, pageSize, keyword, callback) {
    const first = new AV.Query("zitie");
    first.contains("author", keyword);
    const second = new AV.Query("zitie");
    second.contains("name", keyword);
    const query = AV.Query.or(first, second);
    query.limit(pageSize);
    query.descending("createdAt");
    query.skip((currentPage - 1) * pageSize);
    // 查询数据
    var container = document.getElementById("container");
    query.find().then(function (results) {
        results.forEach(function (object) {
            var newDiv = document.createElement("div");
            newDiv.classList.add("card");
            container.appendChild(newDiv);
            var textDiv = document.createElement("div");
            textDiv.classList.add("text");
            newDiv.appendChild(textDiv);
            var nameData = object.get('zitieName');
            var authorData = object.get('author');
            var name = document.createElement("div");
            name.classList.add("name");
            name.textContent = authorData + "·" + nameData;
            textDiv.appendChild(name);
            var newImg = document.createElement("img");
            var imgurl = object.get('cover')
            var decodedUrl = decodeURIComponent(imgurl);
            newImg.src = decodedUrl;
            newDiv.appendChild(newImg);
            newImg.addEventListener('click', function () {
                var imgArr = object.get('imgArr');
                var objectId = object.get('objectId');
                var isLoop = object.get('isLoop');
                var imgType = object.get('imgType');
                var loopNum = object.get('loopNum');
                var author = object.get('author');
                var name = object.get('zitieName');
                localStorage.setItem('imgArr', JSON.stringify(imgArr));
                localStorage.setItem('objectId', objectId);
                localStorage.setItem('imgType', imgType);
                localStorage.setItem('isLoop', isLoop);
                localStorage.setItem('loopNum', loopNum);
                localStorage.setItem('name', name);
                localStorage.setItem('author', author);
                // 跳转到详情页
                window.location.href = 'zitie_today_detail.html';
            });
        })
        callback(results);
    }).catch(function (error) {
        // 处理错误
        // console.error('Error while fetching data:', error);
        // callback();
    });
}
function requestZitie_today_imgs(currentPage, pageSize, zitieId, callback) {
    const query = new AV.Query("zitieImg");
    query.equalTo("zitieId", zitieId);
    query.limit(pageSize);
    // query.descending("createdAt");
    query.skip((currentPage - 1) * pageSize);
    // 查询数据
    query.find().then(function (results) {

        var container = document.getElementById("container");
        results.forEach(function (object) {
            var newImg = document.createElement("img");
            newImg.classList.add("img-fluid");
            var imgurl = object.get('img')
            var decodedUrl = decodeURIComponent(imgurl);
            newImg.src = decodedUrl;
            container.appendChild(newImg);
        });
        callback(results);
    }).catch(function (error) {
        // 处理错误
        // console.error('Error while fetching data:', error);
        // callback();
    });
}
function requestZitie(currentPage, pageSize, keyword, callback) {
    const first = new AV.Query("zitie_pdf2");
    first.contains("author", keyword);
    const second = new AV.Query("zitie_pdf2");
    second.contains("name", keyword);
    const query = AV.Query.or(first, second);
    query.limit(pageSize);
    query.descending("createdAt");
    query.skip((currentPage - 1) * pageSize);
    // 查询数据
    query.find().then(function (results) {
        var poemList = document.getElementById('poem-list');

        results.forEach(function (object) {
            var describeData = object.get('describe');
            // 将数据展示在 HTML 页面上
            var authorData = object.get('author');
            var nameData = object.get('name');
            var describeData = object.get('describe');

            var card = document.createElement('div');
            card.classList.add('poem-card');


            var container = document.createElement('div');
            container.classList.add('poem-container');


            var wrapper = document.createElement('div');
            wrapper.classList.add('image-wrapper');


            var imgurl = object.get('cover')
            var decodedUrl = decodeURIComponent(imgurl);
            var img = document.createElement('img');
            img.src = decodedUrl;
            img.classList.add('poem-cover');
            var name = document.createElement('div');
            name.classList.add('poem-content');
            name.textContent = nameData;
            var author = document.createElement('div');
            author.classList.add('poem-author');
            author.textContent = authorData;
            card.appendChild(name);
            card.appendChild(author);
            container.appendChild(wrapper);
            wrapper.appendChild(img)
            container.appendChild(card);
            poemList.appendChild(container);
            // 为诗词卡片添加点击事件
            card.addEventListener('click', function () {

                localStorage.setItem('selectedZitieCover', imgurl);
                localStorage.setItem('selectedZitieAuthor', authorData);
                localStorage.setItem('selectedZitieName', nameData);
                localStorage.setItem('selectedZitieDescribe', describeData);
                window.location.href = 'zitie_detail.html';
            });
        });
        callback(results);
    }).catch(function (error) {

    });
}


const timeSince = (date) => {
    const seconds = Math.floor((new Date() - date) / 1000);

    let interval = seconds / 31536000;

    if (interval > 1) {
        return Math.floor(interval) + " 年前";
    }
    interval = seconds / 2592000;
    if (interval > 1) {
        return Math.floor(interval) + " 个月前";
    }
    interval = seconds / 86400;
    if (interval > 1) {
        return Math.floor(interval) + " 天前";
    }
    interval = seconds / 3600;
    if (interval > 1) {
        return Math.floor(interval) + " 小时前";
    }
    interval = seconds / 60;
    if (interval > 1) {
        return Math.floor(interval) + " 分钟前";
    }
    if (seconds < 10) {
        return "刚刚";
    }

    return Math.floor(seconds) + " 秒前";
}

function requestDiscovery(currentPage, pageSize, callback) {
    const query = new AV.Query("post");
    query.limit(pageSize);
    // query.descending("createdAt");
    query.skip((currentPage - 1) * pageSize);
    // 查询数据
    query.find().then(function (results) {
        var container = document.getElementById("container");
        results.forEach(function (object) {

            var newDiv = document.createElement("div");
            newDiv.classList.add("card");
            container.appendChild(newDiv);

            var textDiv = document.createElement("div");
            textDiv.classList.add("text");
            newDiv.appendChild(textDiv);

            var nameData = object.get('zitieName');
            var authorData = object.get('author');
            var name = document.createElement("div");
            name.classList.add("name");
            name.textContent = authorData + "·" + nameData;
            textDiv.appendChild(name);

            var newImg = document.createElement("img");
            var imgurl = object.get('cover')
            var decodedUrl = decodeURIComponent(imgurl);
            newImg.src = decodedUrl;
            newDiv.appendChild(newImg);

            newImg.addEventListener('click', function () {
                var imgArr = object.get('imgArr');
                var objectId = object.get('objectId');
                var isLoop = object.get('isLoop');
                var imgType = object.get('imgType');
                var loopNum = object.get('loopNum');
                var author = object.get('author');
                var name = object.get('zitieName');
                localStorage.setItem('imgArr', JSON.stringify(imgArr));

                localStorage.setItem('objectId', objectId);
                localStorage.setItem('imgType', imgType);
                localStorage.setItem('isLoop', isLoop);
                localStorage.setItem('loopNum', loopNum);
                localStorage.setItem('name', name);
                localStorage.setItem('author', author);

                window.location.href = 'zitie_today_detail.html';
            });


        });
        callback(results);
    }).catch(function (error) {
        // 处理错误
    });
}

function requestZidianDictCate(currentPage, pageSize, keyword, callback) {
    const first = new AV.Query("danzi_cate");
    first.contains("author", keyword);
    const second = new AV.Query("danzi_cate");
    second.contains("name", keyword);
    const query = AV.Query.or(first, second);
    query.limit(pageSize);
    query.descending("createdAt");
    query.skip((currentPage - 1) * pageSize);
    // 查询数据
    query.find().then(function (results) {

        var container = document.getElementById('grid-container');
        results.forEach(function (object) {

            var newDiv = document.createElement("div");
            newDiv.classList.add("grid-item");
            var nameData = object.get('name');
            newDiv.textContent = nameData;
            container.appendChild(newDiv);
            newDiv.style.backgroundColor = getRandomDarkColor();

            newDiv.addEventListener('click', function () {
                // var name = object.get('name');
                localStorage.setItem('dict_className', object.get('class_name'));
                localStorage.setItem('dictMore_name', nameData);

                if (nameData == "书法字典") {
                    window.location.href = 'https://mdx.lintiebao.cn';
                } else {
                    window.location.href = 'shufaDict.html';
                }
            });
        })


        callback(results);
    }).catch(function (error) {

    });
}
function getRandomDarkColor() {
    var letters = '012345';
    var color = '#';
    for (var i = 0; i < 3; i++) {
        color += letters[Math.floor(Math.random() * 6)];
    }
    return color;
}
function requestZidianDict(currentPage, pageSize, keyword, callback) {

    var classN = localStorage.getItem('dict_className') ?? "danzi";
    const query = new AV.Query(classN);
    query.contains("name", keyword);
    query.limit(pageSize);
    query.skip((currentPage - 1) * pageSize);
    // 查询数据
    query.find().then(function (results) {
        var container = document.getElementById("container");
        results.forEach(function (object) {
            var newDiv = document.createElement("div");
            newDiv.classList.add("card");
            container.appendChild(newDiv);
            var textDiv = document.createElement("div");
            textDiv.classList.add("text");
            newDiv.appendChild(textDiv);
            var nameData = object.get('name');
            var name = document.createElement("div");
            name.classList.add("name");
            name.textContent = nameData;
            textDiv.appendChild(name);
            var newImg = document.createElement("img");
            var imgurl = object.get('img')
            if (imgurl == undefined) {
                var decodedUrl = decodeURIComponent('https://image.lintiebao.cn/shufa/dic/' + object.get('title') + '.jpg');
                newImg.src = decodedUrl;
            } else {
                const encrypt = new JSEncrypt();
                encrypt.setPrivateKey(key);
                const decryptedData = encrypt.decrypt(imgurl);
                var decodedUrl = decodeURIComponent(decryptedData);
                newImg.src = decodedUrl;
            }
            newDiv.appendChild(newImg);
            newImg.addEventListener('click', function () {
                localStorage.setItem('dict_img', newImg.src);
                localStorage.setItem('dict_name', nameData);
                localStorage.setItem('dict_title', object.get('title'));
                localStorage.setItem('dict_id', object.get('objectId'));
                window.location.href = 'shufaDictDetail.html';
            });
        });
        callback(results);
    }).catch(function (error) {

    });
}
function requestZidianDict(currentPage, pageSize, keyword, callback) {

    var classN = localStorage.getItem('dict_className') ?? "danzi";
    const query = new AV.Query(classN);
    query.contains("name", keyword);
    query.limit(pageSize);
    query.skip((currentPage - 1) * pageSize);
    // 查询数据
    query.find().then(function (results) {
        var container = document.getElementById("container");
        results.forEach(function (object) {
            var newDiv = document.createElement("div");
            newDiv.classList.add("card");
            container.appendChild(newDiv);
            var textDiv = document.createElement("div");
            textDiv.classList.add("text");
            newDiv.appendChild(textDiv);
            var nameData = object.get('name');
            var name = document.createElement("div");
            name.classList.add("name");
            name.textContent = nameData;
            textDiv.appendChild(name);
            var newImg = document.createElement("img");
            var imgurl = object.get('img')
            if (imgurl == undefined) {
                var decodedUrl = decodeURIComponent('https://image.lintiebao.cn/shufa/dic/' + object.get('title') + '.jpg');
                newImg.src = decodedUrl;
            } else {
                const encrypt = new JSEncrypt();
                encrypt.setPrivateKey(key);
                const decryptedData = encrypt.decrypt(imgurl);
                var decodedUrl = decodeURIComponent(decryptedData);
                newImg.src = decodedUrl;
            }
            newDiv.appendChild(newImg);
            newImg.addEventListener('click', function () {
                localStorage.setItem('dict_img', newImg.src);
                localStorage.setItem('dict_name', nameData);
                localStorage.setItem('dict_title', object.get('title'));
                localStorage.setItem('dict_id', object.get('objectId'));
                window.location.href = 'shufaDictDetail.html';
            });
        });
        callback(results);
    }).catch(function (error) {

    });
}
function requestZidianDict2(currentPage, pageSize, characters, callback) {
    let dataArr = new Array(characters.length).fill(null);
    let classN = localStorage.getItem('dict_className') ?? "danzi";
    const maxConcurrentRequests = 1;
    let currentRequest = 0;
    let completedRequests = 0;

    function sendRequest(index) {
        if (index >= characters.length) {
            checkCompletion();
            return;
        }

        const character = characters[index];
        const query = new AV.Query(classN);
        query.contains("name", character);
        query.limit(pageSize);
        query.skip((currentPage - 1) * pageSize);

        if (currentRequest < maxConcurrentRequests) {
            currentRequest++;
            query.find().then(function(results) {
                currentRequest--;
                completedRequests++;

                if (results.length > 0) {
                    const randomIndex = Math.floor(Math.random() * results.length);
                    const result = results[randomIndex];
                    const name = result.get('name');
                    if (name === character) {
                        dataArr[index] = result;
                    }
                }

                checkCompletion();
                sendRequest(index + 1);
            }).catch(function(error) {
                console.log(error);
                currentRequest--;
                completedRequests++;
                checkCompletion();
                sendRequest(index + 1);
            });
        }
    }

    function checkCompletion() {
        if (completedRequests === characters.length) {
            callback(dataArr); // 处理完所有数据后回调
        }
    }

    sendRequest(0); // 从第一个字符开始发送请求
}
function requestZidianDict3(currentPage, pageSize, keyword, callback) {

    var classN = localStorage.getItem('dict_className') ?? "danzi";
    const query = new AV.Query(classN);
    query.contains("name", keyword);
    query.limit(pageSize);
    query.skip((currentPage - 1) * pageSize);
    // 查询数据
    query.find().then(function (results) {
        results.forEach(function (object) { 
        });
        callback(results);
    }).catch(function (error) {

    });
}
function requestKey(callback) {
    const query = new AV.Query("privateKey");
    query.find().then(function (results) {
        callback(results);
    }).catch(function (error) {

    });
}
function cleanDict() {
    var dataContainer = document.getElementById('container');
    dataContainer.innerText = '';
}